package com.mongo.service.impl;

import com.mongo.entity.User;
import com.mongo.service.MongoService;
import com.mongodb.client.result.UpdateResult;
import org.bson.BsonValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuhuan
 * @date 2025/4/18
 */
@Service
public class MongoServiceImpl implements MongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public UpdateResult save(User user) {
        List<String> insertedIds = new ArrayList<>();
        List<String> updatedIds = new ArrayList<>();

        Query query = new Query(new Criteria("_id").is(user.getId()));
        Update update = new Update()
                .set("name", user.getName())
                .set("age", user.getAge());
        UpdateResult result = mongoTemplate.upsert(query, update, User.class);
        BsonValue upsertedId = result.getUpsertedId();
        if (upsertedId != null) {
            insertedIds.add(user.getId());
        } else if (result.getModifiedCount() > 0) {
            updatedIds.add(user.getId());
        }
        System.out.println("插入的 ID: " + insertedIds);
        System.out.println("更新的 ID: " + updatedIds);
        return result;
    }

    @Override
    public User add(User user) {
        return mongoTemplate.save(user, "user");
    }

    @Override
    public UpdateResult edit(User user) {
        Criteria criteria = Criteria.where("id").is(user.getId());
        Update update = new Update();
        update.set("name", user.getName());
        update.set("age", user.getAge());
        return mongoTemplate.updateFirst(Query.query(criteria), update, User.class);
    }
}
